package com.example.fileserver_API.WebScoket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket")
public class WebSocket {
    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "id") String id) {
        if (!sessionPool.containsKey(id)){
            this.session = session;
            webSockets.add(this);
            sessionPool.put(id, session);
            System.out.println(id + "【websocket消息】有新的连接，总数为:" + webSockets.size());
        }
    }

    @OnClose
    public void onClose() {
        if (sessionPool.containsValue(this.session)) {
            Iterator<String> iterator = sessionPool.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (this.session.equals(sessionPool.get(key))) {
                    iterator.remove(); // 使用迭代器的 remove 方法安全删除元素
                }
            }
            webSockets.remove(this);
            System.out.println("【websocket消息】连接断开，总数为:" + webSockets.size());
            System.out.println(webSockets);
        }
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:" + message);
        this.session.getAsyncRemote().sendText("终于等到你~");
    }

    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:" + message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
